package com.bocim.course.service;

import com.bocim.course.dao.Productdao;
import com.bocim.course.meta.Orders;
import com.bocim.course.meta.Product;
import com.bocim.course.meta.ProductList;
import com.bocim.course.serviceImp.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * Created by liujunchen on 2016/11/8.
 */
@Service
public class ProductService implements IProductService{
    @Autowired
    private   Productdao productdao ;
    @Override
    public List<Product> selectAllProduct() {
        List<Product> productList = productdao.selectProductsbyUsers(0) ;
        return productList;
    }

    @Override
    public Product selectById(int productId , int  userId ) {
          Product product    = productdao.selectProductbyId(productId, userId)   ;
        return product ;
    }

    @Override
    public List<Product> selelctProductListByuserId(int userId) {
        ProductList productList  = productdao.selectProductListbyUserId(userId)  ;
        List<Product> productLists =   productList.getProducts();
        return  productLists ;
    }

    @Override
    public boolean deleteProduct(int productId) {
        boolean  result   = (productdao.deleteProduct(productId )==1?true :false )  ;
        return  result ;
    }

    @Override
    public boolean insertProduct(Product product) {
          int result  =  productdao.insertProduct(product) ;
        boolean  flag  = false ;
        if (result ==1){
            flag= true ;
        }
        return  flag  ;
    }

    @Override
    public boolean updateProduct(Product product) {
         boolean flag =  (productdao.updateProduct(product)==1)?true:false;
        return flag;
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public  void   buyProduct(Orders orders ){
        productdao.addOrder(orders) ;
//        throwException();
        productdao.updateProductStatus( orders.getProductId() , 1 ) ;

    }
    private  void throwException(){
        throw new RuntimeException("ERROR") ;
    }

}
